import { Modal, message } from "ant-design-vue";
import { GetCodeDict, GetLanguageList } from '@/api/public';
import { zhCN } from '@/utils/language/zh-CN';
import { arAe } from '@/utils/language/ar-AE';
import { enUs } from '@/utils/language/en-US';
import locale from "@/utils/i18n";
import { Local, Session } from '@/utils/storage';
import { CommonEnum } from "./enums/commonEnum";



/**
 * 取消执行调用接口
 */
export const cancel = () => {
  // 设置一个函数，在执行请求前先执行这个函数
  // 获取缓存的 请求取消标识 数组，取消所有关联的请求
  let cancelArr = window.axiosCancel;
  cancelArr.forEach((ele, index) => {
    // ele.cancel("取消了请求") // 在失败函数中返回这里自定义的错误信
    console.log("取消了请求");
    delete window.axiosCancel[index];
  });
};

export const urlDecodeURIComponent = () => {
  // 创建一个URL对象，传入当前路径
  const url = new URL(window.location.href);

  // 获取查询参数'redirect'
  const redirectParam: any = url.searchParams.get("redirect");
  // 解码参数
  return decodeURIComponent(redirectParam);
};

/**
 * 获取重定向名称
 * @param redirect 重定向地址
 * @returns
 */
export const getRedirect = (redirect: String) => {
  // consolelog("redirect:", redirect);
  let newRedirect = null;
  if (redirect === "/home" || redirect === "home" || redirect === "/") {
    return null;
  }
  if (redirect && redirect.split("/").length > 3) {
    newRedirect = redirect.split("/")[1] + "/" + redirect.split("/")[2];
    //遍历查询跳转名字
  }
  // // consolelog(redirect.split('/'));

  if (redirect && redirect.split("/").length < 3 && redirect.split("/") > 0) {
    newRedirect = redirect.split("/")[1];
  }
  return newRedirect;
};

export const commonResult = (r: any, t: any) => {
  let sign: any = false;
  r.code === 200 && message.success(t(r.msg)), (sign = true);
  r.code !== 200 && message.error(t(r.msg));
  return sign;
};

export function urlToBase64(url: any) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";

    xhr.onload = () => {
      if (xhr.status === 200) {
        const reader = new FileReader();
        reader.onloadend = () => {
          resolve(reader.result);
        };
        reader.readAsDataURL(xhr.response);
      } else {
        reject(
          new Error(
            "Failed to load URL: " + url + " (status code: " + xhr.status + ")"
          )
        );
      }
    };

    xhr.onerror = () => {
      reject(new Error("Failed to load URL: " + url));
    };

    xhr.send();
  });
}

export function urlToBlob(url: any) {
  return new Promise((resolve, reject) => {
    const xhr: any = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(new Error("Failed to load URL: " + xhr.statusText));
      }
    };
    xhr.onerror = function () {
      reject(new Error("Failed to load URL"));
    };
    xhr.send();
  });
}

export function formatFileSize(fileSize: number) {
  if (fileSize < 1024) {
    return fileSize + "B";
  } else if (fileSize < 1024 * 1024) {
    let temp = fileSize / 1024;
    temp = temp.toFixed(2);
    return temp + "KB";
  } else if (fileSize < 1024 * 1024 * 1024) {
    var temp = fileSize / (1024 * 1024);
    temp = temp.toFixed(2);
    return temp + "MB";
  } else {
    var temp = fileSize / (1024 * 1024 * 1024);
    temp = temp.toFixed(2);
    return temp + "GB";
  }
}

export function getCurrentlanguage(proxy: any) {
  // const { proxy } = getCurrentInstance() as any;
  if (proxy) {
    const str = "en-US";
    //  en-US  arabic
    const name =
      proxy.$i18n.locale === "en-US"
        ? "en-US"
        : proxy.$i18n.locale === "arabic"
          ? "arabic"
          : "zh-CN";
    if (str === name) {
      return name;
    }
  } else {
    return null;
  }
}

// 列表转树形结构
export const list2Tree = (data: any) => {
  let res: any = [];
  data.forEach((item: any) => {
    const parent = data.find((node: any) => node.id === item.parentId);
    if (parent) {
      parent.children = parent.children || [];
      parent.children.push(item);
    } else {
      // * 根节点
      res.push(item);
    }
  });
  return res;
};

/*
 * 深度优先遍历树
 * 一个递归方法
 * @params tree:要转换的树结构数据
 * @params parentId:当前遍历节点的父级节点id，初始为null(因为根节点无parentId)
 * */
export function tree2List(tree, list, path = "") {
  if (!Array.isArray(tree)) return [];
  for (const key in tree) {
    if (Object.prototype.hasOwnProperty.call(tree, key)) {
      const value = tree[key];
      if (value.children && value.children.length) {
        path = path + "/" + value.path;
        tree2List(value.children, list, path);
      } else {
        delete value.children;
        value.path = path;
        list.push(value);
      }
    }
  }
}

// 超过字符数显示省略号
export const splitStr = (strs: string, No: number = 15) => {
  if (!strs || !strs.length) return "--";
  if (strs.length <= No) return strs;
  if (strs.length > No) {
    const str = strs.substr(0, No) + "...";
    return str;
  }
};

export const showCurrentLang = (item: any, cn, en, ar) => {

  if (isEmpty(item)) return "";
  if (cn) return item.nameZh;
  if (en) return item.nameEn;
  if (ar) {
    if (item.nameAr) {
      return item.nameAr;
    } else {
      return item.nameEn;
    }
  }
};

export const showCurrentLang2 = (item: any, cn, en, ar) => {
  if (isEmpty(item)) return "";
  if (cn) return item.descZh;
  if (en) return item.dictDesc;
  if (ar) {
    if (item.descAr) {
      return item.descAr;
    } else {
      return item.dictDesc;
    }
  }
};

export const download = (item: object) => {
  let link = document.createElement("a");
  let url = item.filePath;
  // 这里是将url转成blob地址
  fetch(url)
    .then((res) => res.blob())
    .then((blob) => {
      link.href = URL.createObjectURL(blob);
      link.style.display = "none";
      link.download = item.originalFileName;
      link.click();
    });
};

export const DigAnimation = (target = 0, classname: string) => {
  const eles = document.querySelectorAll(`.${classname}`);
  for (const key in eles) {
    if (Object.prototype.hasOwnProperty.call(eles, key)) {
      const ele = eles[key];
      if (!target) {
        ele.innerText = formatNumber(Number(target));
        return
      }
      ele.innerText = 0;
      const upDateNumber = () => {
        // 获取当前div的数值
        const d = Number(ele.innerText);
        // 设置数据增加的值，可以通过target除的数值确定怎么加数值的快慢
        const increment = target / 200;
        // 当数字小于最大值时，执行下面的操作
        if (d < target) {
          // 向上取整
          ele.innerText = `${Math.ceil(d + increment)}`;
          // 1ms重新调用，不然它会在第一次运行完就结束
          setTimeout(upDateNumber, 1);
        } else {
          ele.innerText = formatNumber(Number(target));
        }
      };
      upDateNumber();
    }
  }
};

// 格式化数字 千分位分隔
export const formatNumber = (number: Number) => {
  return number.toLocaleString("en-US");
};

/**
 * 公用获取字典参数
 * @param params 参入参数
 * @returns 
 */
export function getCodeDict(params: any) {
  return new Promise(async (resolve, reject) => {
    const { data, code, msg }: any = await GetCodeDict(params).catch((error) => {
      console.log(error);
    }).finally()
    code === 200 && resolve(data)
    code !== 200 && reject(msg)
  })

}

/**
 * 公用url转base64
 * @param img 
 * @param callback 
 */
export function getURLToBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
}


const languages: any = { zhCN, arAe, enUs }
/**
 * 初始化多语言数据
 * @param setRedis 是否持久化 false:不写 true:写入
 * @param open 是否开放接口  是:true  否:false
 * @returns 
 */
export async function getLanguageList(setRedis: boolean, open: boolean) {
  const { code, data }: any = await GetLanguageList(null, open)
  if (code !== 200) {
    console.error('国际化初始失败！');
    return;
  }
  data?.forEach((r: any) => {
    Object.assign(languages.zhCN, { [r.charKey]: r.descZh });
    Object.assign(languages.arAe, { [r.charKey]: r.descAr });
    Object.assign(languages.enUs, { [r.charKey]: r.descEn });
  })
  locale.global.setLocaleMessage('en-US', languages.enUs);
  locale.global.setLocaleMessage('zh-CN', languages.zhCN);
  locale.global.setLocaleMessage('ar-AE', languages.arAe);
  setRedis && Local.set(CommonEnum.setRedisLocalLanguage, true)
}


/**
 * lineManager idList转成中文
 * @param val 传入参数
 * @param lineManagerList 领导list 
 * @returns 
 */
export const employeeName = (val: any, lineManagerList: any) => {
  try {
    if (val) {
      let i = JSON.parse(val)
      return lineManagerList.filter((item: any) => {
        if (i.includes(Number(item.id))) return true;
      }).map((v: any) => v.fullName).join(",");
    }
  } catch (error) {
    return ""
  }
};

import hooks from '@/hooks';
const { isCn, isEn } = hooks.useLanguage()
export const getName = (value: any, employeeWorkStatus: any) => {
  const name = ref("");
  const obj = ref(null);
  if (value) {
    obj.value = employeeWorkStatus.filter(
      (v: any) => v.dictData == String(value) || Number(value) === Number(v.dictData)
    )[0];
    name.value = isCn.value
      ? obj.value?.descZh
      : isEn.value
        ? obj.value?.dictDesc
        : obj.value?.descAr;
  }
  return name.value;
};

// 根据子级找上级
export const findAllParents = (tree, childId, parents = []) => {
  for (const node of tree) {
    if (node.id === childId) {
      parents.push(node.id);
      return parents;
    }
    if (node.children?.length > 0) {
      const newParents = [...parents, node.id];
      const foundParents = findAllParents(node.children, childId, newParents);
      if (foundParents.length > 0) {
        return foundParents;
      }
    }
  }
  return [];
}

// 根据父级找下级
export const findChildIds = (tree: any, parentId: any) => {
  const result = [];
  function traverse(node) {
    if (node.id === parentId) {
      addChildrenIds(node.children);
    } else if (Array.isArray(node.children)) {
      node.children.forEach((child) => {
        traverse(child);
      });
    }
  }

  function addChildrenIds(children) {
    if (Array.isArray(children)) {
      children.forEach((child) => {
        result.push(child.id);
        addChildrenIds(child.children);
      });
    }
  }

  traverse({ id: 0, children: tree }); // Adding a dummy node to start traversal
  return result;
}

/**
 * 添加动画
 * @param element 元素名称
 * @param animation 动画名称
 * @param prefix 前缀
 * @returns 
 */
export const animateCSS = (element: any, animation: any, prefix = 'animate__') =>
  // We create a Promise and return it
  new Promise((resolve, reject) => {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);
    node.classList.add(`${prefix}animated`, animationName);
    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event: any) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }
    node.addEventListener('animationend', handleAnimationEnd, { once: true });
  });